import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Home from '../views/home'
import Layout from '../views/layout'
import Publish from '../views/publish'
import Article from '../views/article'
import { getItem } from '../utils/author'
// 进度条导入
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    // alias: '/',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        // alias: '/',
        component: Home
      },
      {
        path: '/article',
        component: Article
      },
      {
        path: '/publish',
        component: Publish
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 前置 后置守卫导航
router.beforeEach((to, from, next) => {
  // 进度条开始
  Nprogress.start()

  if (getItem()) {
    // token存在
    if (to.path.toLowerCase() === '/login') {
      next('/home')
    } else {
      next()
    }
  } else {
    // 没有token
    if (to.path.toLowerCase() === '/home') {
      next('/login')
    } else {
      next()
    }
  }
})
router.afterEach((to, from) => {
  Nprogress.done()
})

export default router
